<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="文件名称">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="文件类型" prop="fileTypeValue">
          <el-select
            v-model="queryParams.fileTypeValue"
            placeholder="请选择文件类型"
            clearable
          >
            <el-option
              v-for="dict in dict.type.sys_file_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
      </el-form-item>-->
      <!-- <el-form-item label="文件状态" prop="fileStatusValue">
        <el-select v-model="queryParams.fileStatusValue" placeholder="请选择文件状态" clearable>
          <el-option v-for="dict in dict.type.sys_file_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>-->

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:file:add']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:filet:edit']"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:file:remove']"
            >删除</el-button
          >
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:file:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="printBox"
          :disabled="multiple"
          v-hasPermi="['system:file:print']"
        >打印</el-button>
      </el-col>
      <!-- <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
      ></right-toolbar>-->
    </el-row>

    <el-table
      fit
      v-loading="loading"
      border
      :data="dataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column
        min-width="320"
        fixed
        label="文件名称"
        prop="fileName"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <el-link @click="handleDetailDiag(scope.row)" type="primary">
            {{
            scope.row.fileName
            }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="受控编号" prop="fileCode" :show-overflow-tooltip="true" width="200">
        <template slot-scope="scope">
          <el-link @click="handleDetailDiag(scope.row)" type="primary">
            {{
            scope.row.fileCode
            }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column
        label="分发号"
        min-width="100"
        prop="distributeCode"
        :show-overflow-tooltip="true"
      />
      <el-table-column min-width="100" label="状态" prop="status" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <div>{{ scope.row.status == 4 ? '申请中' : scope.row.status == 2 ? '已领取' : '已回收' }}</div>
        </template>
      </el-table-column>
      <el-table-column
        label="领用人"
        min-width="100"
        prop="operateUserName"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="领用时间" prop="collectTime" width="100" :show-overflow-tooltip="true" />
      <!-- <el-table-column
          label="文件实施日期"
          prop="keyword"
          width="150"
          :show-overflow-tooltip="true"
      />-->
      <el-table-column
        label="经办人"
        prop="collectUserName"
        width="100"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        min-width="100"
        :show-overflow-tooltip="true"
        align="center"
        label="回收经办人"
        prop="retrieveUserName"
      />
      <el-table-column
        label="回收确定时间"
        prop="retrieveTime"
        width="140"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="操作"
        align="center"
        width="250"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.collectUserName"
            size="mini"
            type="text"
            v-hasPermi="['system:file:ly']"
            @click="handleprintArea(scope.row)"
            v-print="print"
          >附件二维码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="pagination"
    />
    <el-dialog :visible.sync="showCode" title="领用二维码" width="300px" append-to-body>
      <div style="text-align: center">
        <vue-qr :text="textUrl" :size="200"></vue-qr>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="showSend" title="领用" width="500px" append-to-body>
      <!-- <el-form ref="form" :model="form" :rules="rules" label-width="120px"> -->
      <!-- <el-form-item label="领用数量" prop="num"> -->
      <div
        style="display: flex;align-items: center;justify-content: center;font-size: 20px;"
      >确定要领用当前二维码吗？</div>
      <!-- <el-input
              v-model="form.num"
              placeholder="请输入领用数量"
              clearable
              :style="{ width: '100%' }"
            >
      </el-input>-->
      <!-- </el-form-item> -->
      <!-- <el-form-item label="文件类型" prop="typeValue">
            <el-select
              v-model="form.typeValue"
              collapse-tags
              :style="{ width: '100%' }"
            >
              <el-option label="原件" :value="1" />
              <el-option label="复印件" :value="2" />
            </el-select>
      </el-form-item>-->
      <!-- </el-form> -->
      <template slot="footer">
        <el-button size="mini" @click="showSend = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="saveSend">确 定</el-button>
      </template>
    </el-dialog>
    <!-- 打印模板位置 -->
    <PrintBox
      :pageNum="queryParams.pageNum"
      :total="total"
      :printRow="printList"
      :checkNum="10"
      :checkLabel="'contentList'"
      id="printBox"
    >
      <template slot="title" slot-scope="scope">
        文件发放/收回记录表 STET/B/03-1
        <!-- <div style="font-size: 14px; margin-top: 5px">
            <span v-if="zlcode.includes(Number(fileTypeValue))"
              >（质量活动记录表格 （通用类、标定类、各类试验物质及设备验收类、
              辅助类、期间核查类）</span
            >
  
            <span v-if="wlwjcode.includes(Number(fileTypeValue))"
              >(往来文件(本公司发文、上级单位来文、外单位来文))</span
            >
            <span v-if="[6, 15, 16].includes(Number(fileTypeValue))"
              >(质量手册、资源手册、程序文件)</span
            >
            <span
              v-if="[7, 8, 10, 11, 12, 113, 14].includes(Number(fileTypeValue))"
              >(作业指导书)</span
            >
            <span
              v-if="[23, 24, 25, 26, 27, 28, 29,30,31,32,33,34].includes(Number(fileTypeValue))"
              >(质量活动记录表格（原始观测数据、记录、检测报告）)</span
            >
            <span v-if="fileTypeValue == 22">(检测方法)</span>
        </div>-->
      </template>
      <template slot-scope="scope" style="position: relative;">
        <!-- <div style="position: absolute; top: 10px;left: 10px;">
                <img src="../../../../assets/images/watermark.png" alt="" style="width: 200px;height: 80px;">
        </div>-->
        <!-- 表格  class  table-page  必须-->
        <table style="border-collapse: collapse" border="1" cellspacing="0" class="table-page">
          <thead>
            <tr class="table_header">
              <th style="width: 20mm">序号</th>
              <th style="width: 45mm">文件名称</th>
              <th style="width: 30mm">受控号</th>
              <th style="width: 30mm">分发号</th>
              <th style="width: 55mm">状态</th>

              <th style="width: 65mm">领用人</th>
              <th style="width: 50mm">领用时间</th>
              <th style="width: 50mm">经办人</th>
              <th style="width: 50mm">回收经办人</th>
              <th style="width: 50mm">回收确定时间</th>

              <!-- <th
                  style="width: 50mm"
                  v-if="wlwjcode.includes(Number(fileTypeValue))"
                >
                  文件下发日期
              </th>-->
            </tr>
          </thead>
          <!-- 同列表接口数据 -->
          <tbody>
            <tr v-for="(e, i) in 10">
              <td>{{ scope.item.contentList[i] && scope.item.contentList[i].serialNumber+1 }}</td>

              <td style="width: 100mm;">
                {{
                scope.item.contentList[i] &&
                scope.item.contentList[i].fileName
                }}
              </td>
              <td>
                {{
                (scope.item.contentList[i] &&
                scope.item.contentList[i].fileCode) ||
                ""
                }}
              </td>
              <td>
                {{
                (scope.item.contentList[i] &&
                scope.item.contentList[i].distributeCode) ||
                ""
                }}
              </td>
              <td>
                {{
                scope.item.contentList[i] &&
                scope.item.contentList[i].status == 4 ? '申请中' : scope.item.contentList[i] && scope.item.contentList[i].status == 2 ? '已领取' :scope.item.contentList[i] && scope.item.contentList[i].status == 3? '已回收' :''
                }}
              </td>
              <td>
                {{
                scope.item.contentList[i] &&
                scope.item.contentList[i].operateUserName
                }}
              </td>

              <td>
                {{
                scope.item.contentList[i] &&
                scope.item.contentList[i].collectTime
                }}
              </td>
              <td>
                {{
                scope.item.contentList[i] &&
                scope.item.contentList[i].collectUserName
                }}
              </td>
              <td>
                {{
                scope.item.contentList[i] &&
                scope.item.contentList[i].retrieveUserName
                }}
              </td>
              <td>
                {{
                scope.item.contentList[i] &&
                scope.item.contentList[i].retrieveTime
                }}
              </td>
            </tr>
          </tbody>
        </table>
        <div class="page-bottom" style="page-break-after: always">
          <div class="desc">注：本表格自2021年8月1日起生效</div>
        </div>
      </template>
    </PrintBox>
    <!-- <Detail ref="Detail" :id="id"></Detail> -->
    <!-- 小票打印 -->
    <div id="printArea" class="noprint">
      <div class="printWait">
        <table border="1" class="table-page">
          <tr>
            <td colspan="3" style="width: 10mm;font-size: 8px;white-space: nowrap;">受控编号：</td>
            <td colspan="1" style="width: 30mm;font-size: 9px;">{{ printItem.fileCode }}</td>
          </tr>
          <tr>
            <td colspan="3" style="width: 10mm;font-size: 10px">分发号：</td>
            <td colspan="1" style="width: 30mm;font-size: 10px">{{ printItem.distributeCode }}</td>
          </tr>
          <tr>
            <td colspan="3" style="width: 10mm;font-size: 10px">领用人：</td>
            <td colspan="1" style="width: 30mm;font-size: 10px;white-space: nowrap;">
              <img style="width: 100%;height: 20px;" :src="baseUrl+printItem.esign" alt />
            </td>
          </tr>
        </table>
        <div
          style="text-align: center;width: 100%;margin-top: 5px;display: flex;align-items: center; justify-content: center;"
        >
          <vue-qr :text="textUrl" :size="80" :margin="5"></vue-qr>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import store from "@/store";
import printStyle from "@/utils/print.js";
import { listFileRecord } from "@/api/system/recDisrecord.js";
import { listFileManager, delFileManager } from "@/api/system/fileManager.js";
import { fileGetAdd } from "@/api/system/fileManagerRecord.js";
//   import Detail from "./detail.vue";
export default {
  name: "listFileManager",
  components: {
    //   Detail,
  },
  dicts: ["sys_file_type", "sys_file_status"],
  data() {
    return {
      baseUrl: this.$VUE_APP_IMG_API,
      printItem: {},
      print: {
        id: "printArea",
        popTitle: "打印", // 打印配置页上方标题
        extraHead: "", //最上方的头部文字，附加在head标签上的额外标签,使用逗号分隔
        preview: false, // 是否启动预览模式，默认是false（开启预览模式，可以先预览后打印）
        previewTitle: "", // 打印预览的标题（开启预览模式后出现）,
        previewPrintBtnLabel: "", // 打印预览的标题的下方按钮文本，点击可进入打印（开启预览模式后出现）
        zIndex: "", // 预览的窗口的z-index，默认是 20002（此值要高一些，这涉及到预览模式是否显示在最上面）
        url: "",
        standard: "",
        extraCss: ""
      },
      id: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      dataList: [],
      // 弹出层标题
      // 日期范围
      dateRange: [],
      // 数据范围选项
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: 1,
        ids: []
      },
      showCode: false,
      current: {},
      showSend: false,
      form: {},
      rules: {
        typeValue: [
          {
            required: true,
            message: "请选择类型",
            trigger: "change"
          }
        ],
        num: [
          {
            required: true,
            message: "输入数量",
            trigger: "blur"
          }
        ]
      },
      textUrl: "",
      infos: [],
      printList: [],
      fileTypeValue: 0,
      zlcode: [21, 20, 19, 18, 17], //质量活动记录表格
      wlwjcode: [2, 3, 4, 5] //外来文件
    };
  },
  // 22--
  created() {
    this.getList();
  },
  methods: {
    printBox() {
      //infos  勾选的数据 如果有勾选就打印勾选。
      if (this.infos.length) {
        this.printList = [
          {
            contentList: this.infos
          }
        ];
      } else {
        //反之打印当前整个列表
        this.printList = [
          {
            contentList: this.dataList
          }
        ];
      }
      // 7, 8, 10, 11, 12, 113, 14
      // 6, 15, 16
      // zlcode
      // wlwjcode
      let flag = false;
      let e = this.printList[0].contentList[0].fileTypeValue;
      if ([7, 8, 10, 11, 12, 113, 14].includes(Number(e))) {
        flag = this.printList[0].contentList.some(
          e => ![7, 8, 10, 11, 12, 113, 14].includes(Number(e.fileTypeValue))
        );
      } else if ([6, 15, 16].includes(Number(e))) {
        flag = this.printList[0].contentList.some(
          e => ![6, 15, 16].includes(Number(e.fileTypeValue))
        );
      } else if (this.zlcode.includes(Number(e))) {
        flag = this.printList[0].contentList.some(
          e => !this.zlcode.includes(Number(e.fileTypeValue))
        );
      } else if (this.wlwjcode.includes(Number(e))) {
        flag = this.printList[0].contentList.some(
          e => !this.wlwjcode.includes(Number(e.fileTypeValue))
        );
      } else if (
        [23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34].includes(Number(e))
      ) {
        flag = this.printList[0].contentList.some(
          e =>
            ![23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34].includes(
              Number(e.fileTypeValue)
            )
        );
      }
      if (flag) {
        this.$modal.msgWarning("多选数据 请保持类型一致");
        return;
      }
      this.fileTypeValue = this.printList[0].contentList[0].fileTypeValue;

      setTimeout(() => {
        this.$print({
          printable: "printBox", //打印区域id
          type: "html", //打印类型是html
          scanStyles: false,
          targetStyles: ["*"],
          style: this.workStyle()
        });
      }, 500);
    },
    // 可以自定义样式  printStyle 是公共样式 切勿私自修改
    workStyle() {
      return `${printStyle}
           table,
        table tr th,
        table tr td {
          height: 10mm;
          padding:7px
        }
        tr {
          page-break-inside: avoid;
        }
        .desc{
        text-align: left; font-size: 12px; margin-top: 10px
      }
        .table_header{
          font-size:16px;
        }
        `;
    },
    changeUser(e) {
      this.form.user = e.nickName;
    },
    pagination() {
      this.queryParams.ids = [];
      this.getList();
    },
    saveSend() {
      // this.$refs["form"].validate((valid) => {
      //   if (valid) {
      // (this.form.fileRecordId = this.current.fileRecordId),
      //   fileGetAdd(this.form).then((response) => {
      //     this.$modal.msgSuccess("操作成功");
      //     this.showSend = false;
      //     this.getList();
      //   });
      // }
      // });
    },
    handleSend(e) {
      this.form = {};
      this.current = e;
      this.showSend = true;
    },
    handleAddHistory(e) {
      this.form = {};
      this.current = e;
      // this.showSend = true;
      this.form.fileRecordId = this.current.fileRecordId;
      this.form.num = "1";
      this.$alert("确定要领用当前二维码吗？", "领用", {
        confirmButtonText: "确定",
        callback: action => {
          fileGetAdd(this.form).then(response => {
            this.$modal.msgSuccess("操作成功");
            this.showSend = false;
            this.getList();
          });
        }
      });
      // }
    },
    handleprintArea(e) {
      console.log(e, "consumeGoodsJoinId");
      this.printItem = e;
      // this.textUrl =
      // process.env.VUE_APP_CODE_API + "fileUrl?url=" + e.fileUrl;
      // this.textUrl = 'https://boss.jsstet-oa.com'  + e.fileUrl;
      this.textUrl =
        process.env.VUE_APP_CODE_API + "fileManager?id=" + e.fileManagerId;
      console.log(this.textUrl);
    },
    userSelect() {
      userSelect().then(response => {
        this.userList = response.data;
      });
    },
    // 获取文件名称
    getFileName(name) {
      console.log(name);
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    getList() {
      this.loading = true;
      listFileRecord(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.typeValue = data.value;
      this.handleQuery();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleDetail(row) {
      this.$router.push("./addFile?isInfo=true&id=" + row.fileRecordId);
    },
    handleDetailDiag(e) {
      this.$refs.Detail.show(e.fileRecordId);
    },
    handleCode(res) {
      this.textUrl =
        process.env.VUE_APP_CODE_API + "fileManager?id=" + res.fileRecordId;

      this.showCode = true;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileRecordId);
      this.infos = selection;
      this.single = selection.length != 1;
      this.multiple = !selection.length;
      this.queryParams.ids = this.ids;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push("./addFile");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const configId = row.fileRecordId || this.ids;
      this.$router.push("./addFile?isEdit=true&id=" + configId);
    },
    handleExport() {
      console.log(this.queryParams);
      this.download(
        "system/fileRecord/export",
        {
          ...this.queryParams
        },
        `文件发放/收回记录表_${this.parseTime(
          new Date().getTime(),
          "{y}-{m}-{d}"
        )}.xlsx`
      );
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.fileRecordId || this.ids;
      let name = this.checkRow(
        userIds,
        this.dataList,
        "fileRecordId",
        "DELETE",
        "fileName"
      );
      this.$modal
        .confirm('是否确认删除文件名称为"' + name + '"的数据项？')
        .then(function() {
          return delFileManager(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    }
  }
};
</script>
<style>
@media print {
  .noprint {
    display: block !important;
    padding-top: 10px;
  }
}
@page {
  size: auto;
  margin: 0mm;
}
table {
  border-collapse: collapse;
}
.procedure {
  word-wrap: break-word;
}
</style>
<style lang="scss" scoped>
.noprint {
  display: none;
}

#printArea {
  // width: 200px;
  // height: 80px;

  // margin: 10px auto;
  .printWait {
    text-align: center;

    .table-page {
      // width: 100%;
    }
    // width: 100%;
    box-sizing: border-box;
    // display: flex;
    // align-items: center;
    // justify-content: space-between;

    .item {
      font-size: 10px;
      // border-bottom: 1px solid #333;
    }
  }
}

::v-deep .el-dialog__body {
  img {
    width: 100%;
  }
}
</style>